package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.PermissionService;
import cn.wolfcode.wms.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;

    public void deleteById(Long id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    public void updateOrSave(Permission permission) {
        if (permission.getId() != null) {
            permissionMapper.updateByPrimaryKey(permission);
        } else {
            permissionMapper.insert(permission);
        }
    }

    public Permission getById(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer totalCount = permissionMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult(qo.getPageSize());
        }
        List<Permission> data = permissionMapper.queryForList(qo);
        return new PageResult(totalCount,data,  qo.getCurrentPage(), qo.getPageSize());
    }

    public void load() {
        permissionMapper.deleteAll();
        //从容器中获得所有的controller对象
        Collection<Object> beans = ctx.getBeansWithAnnotation(Controller.class).values();
        //获取controller中所有的方法对象
        for (Object bean : beans) {
            Method[] ms = bean.getClass().getDeclaredMethods();
            for (Method m : ms) {
                //判断每一个方法是否有权限注解
                RequiredPermission anno = m.getAnnotation(RequiredPermission.class);
                if (anno != null) {
                    //拿到方法的权限表达式

                    String sc = m.getDeclaringClass().getName()+":";
                    String sm = m.getName();
                    String expression = sc+sm;
                    Permission p = new Permission();
                    String name = anno.value();
                    p.setName(name);
                    p.setExpression(expression);
                    //保存到数据库
                    permissionMapper.insert(p);
                }
            }
        }
    }
}
